package com.ly.homework;

import java.util.Scanner;

/**
 * b线程控制a线程退出
 */
public class Homework01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        a.start();
        b.start();
    }
}
//创建A线程类
class A extends Thread{
    private boolean loop = true;
    @Override
    public void run() {
        //输出1到100的数
        while (loop){
            System.out.println((int)(Math.random()*100+1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("线程A退出");
    }

    public boolean isLoop() {
        return loop;
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}
//第二个线程控制第一线程
class B extends Thread{
    private A a;
    private Scanner scanner=new Scanner(System.in);

    public B(A a) {//构造器中直接传入A对象
        this.a = a;
    }

    @Override
    public void run() {
        //接收到用户的输入
        while (true){
            //接收到用户输入
            System.out.println("请输入你的指令Q表式退出;");
            char key = scanner.next().toUpperCase().charAt(0);
            if (key=='Q'){
                //以通的方式结束A方式
                a.setLoop(false);
                System.out.println("b线程退出");
                break;
            }

        }

    }

}
